#include "stdafx.h"

TextFileWriter::TextFileWriter(const wstring& fileName)
{
	m_good = true;
	if (!PathFileExists(fileName.c_str()))
	{
#ifdef _UNICODE
		_wfopen_s( &m_file, fileName.c_str(), L"wt+,ccs=UTF-16LE" );
#else
		_wfopen_s( &m_file, fileName.c_str(), L"wt+,ccs=UNICODE" );
#endif
	}
	else
	{
		_wfopen_s( &m_file, fileName.c_str(), L"wt+,ccs=UTF-16LE");
	}

	if (m_file == NULL)
	{
		wprintf(L"_wfopen failed!\n");
		m_good = false;
	}
}

TextFileWriter::~TextFileWriter()
{
	fclose(m_file);
}

void TextFileWriter::write(const wstring& str)
{
	if ( fwrite(str.c_str(), sizeof(wchar_t), str.size(), m_file) != str.size())
	{
		wprintf(L"fwrite failed!\n");
		m_good = false;
	}
}

void TextFileWriter::writeLine(const wstring& str)
{
	wstring tmp(str);
	tmp.append(L"\n");
	if ( fwrite(tmp.c_str(), sizeof(wchar_t), tmp.size(), m_file) != tmp.size())
	{
		wprintf(L"fwrite failed!\n");
		m_good = false;
	}
}

bool TextFileWriter::good()
{
	return m_good;
}